<?php
// +----------------------------------------------------------------------
// | excel
// +----------------------------------------------------------------------
// | Author: myh
// +----------------------------------------------------------------------
namespace app\common\lib\phpspreadsheet;

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class Excel
{   
    /**
     * 浏览器直接导出excel
     *
     * @param array $data 导出的数据
     * @param string $header 标题
     * @param string $fields 字段名
     */
    public static function export($data, $header, $fields){
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->setActiveSheetIndex(0);
        
        $cell = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
        if (!empty($header)) {
            $h = explode(',', $header);
            for ($i=0; $i < count($h); $i++) {
                $sheet->setCellValue($cell[$i].'1', $h[$i]);
            }
        }
        

        $fields = explode(',', $fields);
        $j = 2;
        foreach ($data as $key => $value) {
            for ($i=0; $i < count($fields); $i++) {
                $sheet->setCellValue($cell[$i].$j, $value[$fields[$i]]);
            }
            $j++;
        }

        // Redirect output to a client’s web browser (Xlsx)
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'.date("Y-m-d", time()).'.xlsx"');
        header('Cache-Control: max-age=0');
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');

        // If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0

        $writer = new Xlsx($spreadsheet);
        $writer->save('php://output');
        exit;
    }
}
